package admin

import (
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// 获取系统提示词列表
func (h *AdminHandler) GetSystemPrompts(c echo.Context) error {
	systemPrompts, err := h.repos.GetSystemPrompt().GetAllSystemPrompts(c.Request().Context())
	if err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	// 转换为响应格式
	rows := make([]SystemPromptRow, 0, len(systemPrompts))
	for _, sp := range systemPrompts {
		rows = append(rows, SystemPromptRow{
			ID:        sp.ID,
			Name:      sp.Name,
			Content:   sp.Content,
			IsActive:  sp.IsActive,
			CreatedAt: sp.CreatedAt.Unix(),
			UpdatedAt: sp.UpdatedAt.Unix(),
		})
	}

	responseData := GetSystemPromptsResponse{
		Rows:  rows,
		Total: len(rows),
	}

	return response.Success(c, responseData)
}

// 创建系统提示词
func (h *AdminHandler) CreateSystemPrompt(c echo.Context) error {
	var req CreateSystemPromptRequest
	if err := c.Bind(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Invalid request body")
	}

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	// 检查名称是否已存在
	if _, err := h.repos.GetSystemPrompt().GetSystemPromptByName(c.Request().Context(), req.Name); err == nil {
		return response.Conflict(c, "System prompt name already exists")
	}

	systemPrompt := &entity.SystemPrompt{
		Name:     req.Name,
		Content:  req.Content,
		IsActive: req.IsActive,
	}

	if err := h.repos.GetSystemPrompt().CreateSystemPrompt(c.Request().Context(), systemPrompt); err != nil {
		return response.InternalServerError(c, "Failed to create system prompt")
	}

	// 如果设置为激活状态，刷新AgentHub
	if req.IsActive {
		h.agentHub.ReloadSystemPromptFromDB()
	}

	responseData := CreateSystemPromptResponse{
		ID:       systemPrompt.ID,
		Name:     systemPrompt.Name,
		IsActive: systemPrompt.IsActive,
	}

	return response.Success(c, responseData)
}

// 更新系统提示词
func (h *AdminHandler) UpdateSystemPrompt(c echo.Context) error {
	var reqDto UpdateSystemPromptRequest
	if err := c.Bind(&reqDto); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.validator.Struct(&reqDto); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Validation failed: "+err.Error())
	}

	id := reqDto.ID

	// 获取现有的系统提示词
	systemPrompt, err := h.repos.GetSystemPrompt().GetSystemPromptByID(c.Request().Context(), id)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "System prompt not found")
		}
		return response.InternalServerError(c, "Database error")
	}

	if reqDto.Name != nil && *reqDto.Name != systemPrompt.Name {
		// 更新字段
		systemPrompt.Name = *reqDto.Name
	}
	if reqDto.Content != nil && *reqDto.Content != systemPrompt.Content {
		// 更新字段
		systemPrompt.Content = *reqDto.Content
	}
	if reqDto.IsActive != nil && *reqDto.IsActive != systemPrompt.IsActive {
		// 更新字段
		systemPrompt.IsActive = *reqDto.IsActive
	}

	if err := h.repos.GetSystemPrompt().UpdateSystemPrompt(c.Request().Context(), systemPrompt); err != nil {
		return response.InternalServerError(c, "Failed to update system prompt")
	}

	// 如果这是激活的提示词，或者将要被激活，刷新AgentHub
	if systemPrompt.IsActive || (reqDto.IsActive != nil && *reqDto.IsActive) {
		h.agentHub.ReloadSystemPromptFromDB()
	}

	return response.Success(c, nil)
}

// 删除系统提示词
func (h *AdminHandler) DeleteSystemPrompt(c echo.Context) error {
	var params DeleteSystemPromptByIdRequest
	if err := c.Bind(&params); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.validator.Struct(&params); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Validation failed: "+err.Error())
	}

	// 检查是否为激活状态
	systemPrompt, err := h.repos.GetSystemPrompt().GetSystemPromptByID(c.Request().Context(), params.ID)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "System prompt not found")
		}
		return response.InternalServerError(c, "Database error")
	}

	if systemPrompt.IsActive {
		return response.BadRequest(c, "Cannot delete active system prompt")
	}

	if err := h.repos.GetSystemPrompt().DeleteSystemPrompt(c.Request().Context(), systemPrompt.ID); err != nil {
		return response.InternalServerError(c, "Failed to delete system prompt")
	}

	return response.Success(c, nil)
}

// 设置激活的系统提示词
func (h *AdminHandler) SetActiveSystemPrompt(c echo.Context) error {
	var params SetActiveSystemPromptByIdRequest
	if err := c.Bind(&params); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if err := h.validator.Struct(&params); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Validation failed: "+err.Error())
	}

	id := params.ID

	if err := h.repos.GetSystemPrompt().SetActiveSystemPrompt(c.Request().Context(), id); err != nil {
		if err == gorm.ErrRecordNotFound {
			return response.NotFound(c, "System prompt not found")
		}
		return response.InternalServerError(c, "Failed to set active system prompt")
	}

	// 刷新AgentHub
	h.agentHub.ReloadSystemPromptFromDB()

	return response.Success(c, nil)
}

// Token使用统计
func (h *AdminHandler) GetTokenUsageStats(c echo.Context) error {
	var req GetTokenUsageStatsRequest
	req.StartDate = c.QueryParam("startDate")
	req.EndDate = c.QueryParam("endDate")

	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "Validation failed: "+err.Error())
	}

	query := h.db.Model(&entity.ClientMessage{}).Where("role = ? AND tokens_used > 0", "assistant")

	if req.StartDate != "" {
		if startTime, err := time.Parse("2006-01-02", req.StartDate); err == nil {
			query = query.Where("created_at >= ?", startTime)
		}
	}

	if req.EndDate != "" {
		if endTime, err := time.Parse("2006-01-02", req.EndDate); err == nil {
			endTime = endTime.Add(24 * time.Hour) // 包含整天
			query = query.Where("created_at < ?", endTime)
		}
	}

	// 总token使用量
	var totalTokens int64
	query.Select("COALESCE(SUM(tokens_used), 0)").Scan(&totalTokens)

	// 总消息数
	var totalMessages int64
	query.Count(&totalMessages)

	// 按日期统计
	var dailyStats []DailyStats
	query.Select("DATE(created_at) as date, COALESCE(SUM(tokens_used), 0) as tokens_used, COUNT(*) as message_count").
		Group("DATE(created_at)").
		Order("date DESC").
		Limit(30).
		Scan(&dailyStats)

	// 按用户统计前10
	var userStats []UserStats
	h.db.Table("client_messages").
		Select("client_messages.user_id, users.username, COALESCE(SUM(client_messages.tokens_used), 0) as tokens_used, COUNT(*) as message_count").
		Joins("LEFT JOIN users ON users.id = client_messages.user_id").
		Where("client_messages.role = ? AND client_messages.tokens_used > 0", "assistant").
		Group("client_messages.user_id, users.username").
		Order("tokens_used DESC").
		Limit(10).
		Scan(&userStats)

	avgTokensPerMessage := float64(0)
	if totalMessages > 0 {
		avgTokensPerMessage = float64(totalTokens) / float64(totalMessages)
	}

	responseData := GetTokenUsageStatsResponse{
		Summary: TokenUsageSummary{
			TotalTokens:         totalTokens,
			TotalMessages:       totalMessages,
			AvgTokensPerMessage: avgTokensPerMessage,
		},
		DailyStats: dailyStats,
		UserStats:  userStats,
	}

	return response.Success(c, responseData)
}
